#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import threading
from pathlib import Path
from typing import Dict, Any
# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent.parent))
from common.utils import LogUtil, api
from common.config import WORK_PATH, ServiceConfig
from dev_server.zmq_server import ZmqServer
from dev_server.device_context_mgr import DeviceContextMgr

logger = LogUtil.get_logger(__name__)

class UiTestService:
    """设备UiTest服务，使用ZMQ处理UiTest请求"""
    
    def __init__(self, zmq_mgr: ZmqServer, device_context_mgr: DeviceContextMgr):
        self.__apis = {}
        self.__register_apis()
        self.host = None
        self.port = None
        self._running = False
        self.service_thread = None
        self.zmq_mgr = zmq_mgr
        self.device_context_mgr = device_context_mgr

        self.service_thread = threading.Thread(target=self.__process_request, daemon=True)

    def destroy(self):
        """销毁UiTest服务"""
        self._running = False
        if self.service_thread:
            self.service_thread.join()
        self.service_thread = None
        self.device_context_mgr = None
        self.zmq_mgr = None
        logger.info("设备UiTest服务关闭")
    
    def __del__(self):
        """析构函数, 释放资源"""
        self.destroy()

    def __register_apis(self):
        """自动注册所有带有@api装饰器的方法"""
        for name in dir(self.__class__):
            if name.startswith('_'):
                continue
            try:
                method = getattr(self.__class__, name)
                if callable(method) and hasattr(method, '_is_api'):
                    api_name = getattr(method, '_api_name', name)
                    self.__apis[api_name] = getattr(self, name)
                    logger.debug(f"Registered API: {api_name} -> {name}")
            except Exception as e:
                # 跳过可能引起问题的属性
                logger.error(f"Error registering API {name}: {e}")
                continue

    def __process_request(self):
        """运行API应答服务主循环"""
        while self._running:
            request, success = self.zmq_mgr.recv_json()
            if success is False:
                continue

            logger.debug(f"UiTest请求: {request}")
            
            api_name = None
            api_args = None
            if request is not None:
                api_name = request.pop('api')
                api_args = request
            
            response = { 'status': 'err', 'result': f'API {api_name} not found' }
            api_func = self.__apis.get(api_name, None)
            if api_func:
                response = { 'status': 'ok', 'result': api_func(**api_args) }
            
            logger.debug(f"UiTest响应: {response}")

            self.zmq_mgr.send_json(response)

        logger.info("UiTest服务主循环结束")

    def start(self):
        # 启动服务线程
        self._running = True
        self.service_thread.start()
        logger.info(f"UiTest服务启动成功，端口: {ServiceConfig.ZMQ_REP_PORT}")

    def is_alive(self) -> bool:
        """检查UiTest服务是否正在运行"""
        return self.service_thread and self.service_thread.is_alive()

    @api()
    def load_devices(self) -> Dict[str, Any]:
        """获取当前连接的设备列表"""
        return self.device_context_mgr.list_cached_devices()

    @api()
    def capture_screen(self, sn: str, filename: str) -> str:
        """捕获设备屏幕"""
        filepath = self.device_context_mgr.capture_screen(sn, filename)
        if filepath is None:
            return None
        image_url = f"http://{self.host}:{self.port}/{sn}/{filename}"
        return image_url